package com.hopu.v1.service.admin.exam.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.exception.BusinessException;
import com.hopu.v1.mapper.admin.classes.StudentMapper;
import com.hopu.v1.mapper.admin.exam.ExamGradesMapper;
import com.hopu.v1.mapper.admin.exam.ExamOptionAnswerMapper;
import com.hopu.v1.mapper.admin.exam.ExamRecordsMapper;
import com.hopu.v1.pojo.exam.*;
import com.hopu.v1.pojo.question.ErrorNotebooksQuestions;
import com.hopu.v1.service.admin.exam.ExamGradesService;
import com.hopu.v1.service.admin.exam.ExamQuestionsService;
import com.hopu.v1.service.front.exam.EStudentRecordsService;
import com.hopu.v1.service.front.question.FErrorNotebooksQuestionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
* @author lihao
* @description 针对表【t_exam_grades(考试成绩表)】的数据库操作Service实现
* @createDate 2024-09-25 11:24:44
*/
@Service
public class ExamGradesServiceImpl extends ServiceImpl<ExamGradesMapper, ExamGrades>
    implements ExamGradesService {

    @Autowired
    private ExamGradesMapper examGradesMapper;
    @Autowired
    private ExamRecordsMapper examRecordsMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private FErrorNotebooksQuestionsService fErrorNotebooksQuestionsService;
    @Autowired
    private ExamQuestionsService examQuestionsService;
    @Autowired
    private ExamOptionAnswerMapper examOptionAnswerMapper;
    @Autowired
    private EStudentRecordsService eStudentRecordsService;
    /**
     * 新增
     * @param examGrades
     */
    @Override
    public void add(ExamGrades examGrades) {
        examGrades.setCreateTime(LocalDateTime.now());
        save(examGrades);
    }

    /**
     * 修改
     * @param examGrades
     */
    @Override
    public void update(ExamGrades examGrades) {
        if(examGradesMapper.selectById(examGrades.getId()) != null) {
            examGrades.setUpdateTime(LocalDateTime.now());
            updateById(examGrades);
        }else{
            throw new BusinessException("记录不存在");
        }
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void del(Integer id) {
        if(examGradesMapper.selectById(id) == null) {
            throw new BusinessException("记录不存在");
        }else{
            examGradesMapper.deleteById(id);
        }
    }

    /**
     * 查询列表
     * @param page
     * @param examGrades
     * @param endTime
     * @return
     */
    @Override
    public IPage<ExamGrades> selectList(Page<ExamGrades> page, ExamGrades examGrades, String endTime) {
        LambdaQueryWrapper<ExamGrades> wrapper = new LambdaQueryWrapper<>();
        if (examGrades.getCreateTime() != null) {
            wrapper.between(ExamGrades::getCreateTime, examGrades.getCreateTime(),endTime);
        }
        wrapper.orderByDesc(ExamGrades::getCreateTime);
        return examGradesMapper.selectPage(page, wrapper);
    }

    @Transactional
    @Override
    public void batchDel(ArrayList<Integer> ids) {
        if (ids.isEmpty()){
            throw new BusinessException("ids不能为空");
        }else{
            examGradesMapper.deleteByIds(ids);
        }
    }

    @Transactional
    @Override
    public void batchAdd(List<ExamGrades> examGradesList) {
        LocalDateTime now = LocalDateTime.now();
        examGradesList.stream().forEach(examGrades -> {examGrades.setCreateTime(now);});
        examGradesMapper.insert(examGradesList);
        LambdaQueryWrapper<ExamRecords> queryWrapper = new LambdaQueryWrapper<ExamRecords>();
        queryWrapper.eq(ExamRecords::getId, examGradesList.get(0).getExamRecordId());
        ExamRecords examRecords = examRecordsMapper.selectById(queryWrapper);
        examRecords.setQuestionExamStatus(1);
        examRecordsMapper.updateById(examRecords);
    }

    /**
     * 根据考试记录Id和题目Id查询学生答案
     *
     * @param examRecordId questionId
     * @return
     */
    @Transactional
    @Override
    public List<ExamGrades> selectGrades(Integer examRecordId, String classId) {
        //获取考试学生学号
        List<String> studentIdList = eStudentRecordsService.list(new LambdaQueryWrapper<ExamStudentRecords>()
                .eq(ExamStudentRecords::getExamRecordId,examRecordId).eq(ExamStudentRecords::getExamStatus, "2")).stream().map(ExamStudentRecords::getStudentId).toList();
        System.out.println(studentIdList);
        //获取考试试卷主观题题号
        List<Integer> questionList = examQuestionsService.list(new LambdaQueryWrapper<ExamQuestions>()
                .eq(ExamQuestions::getExamRecordId, examRecordId).eq(ExamQuestions::getQuestionType, "3")).stream().map(ExamQuestions::getId).toList();
        //存储班级学生回答的答案
        List<ExamGrades> examGradesList = new ArrayList<>();
        for (Integer questionId : questionList) {
            for (String studentId : studentIdList) {
               examGradesList.add(examGradesMapper.selectOne(new LambdaQueryWrapper<ExamGrades>()
                       .eq(ExamGrades::getExamRecordId, examRecordId).eq(ExamGrades::getQuestionId, questionId).eq(ExamGrades::getStudentId, studentId)));
            }
        }
        return examGradesList;
    }
    /**
     * 批改成绩
     * @param examGradesList
     * @return
     */
    @Transactional
    @Override
    public void gradeCorrection(List<ExamGrades> examGradesList) {
        double score = 0.0;
        for (ExamGrades examGrades : examGradesList) {
            //将学生错题加入到错题本
            ExamQuestions examQuestions = examQuestionsService.getById(examGrades.getQuestionId());
            if(!Objects.equals(examGrades.getScore(), examQuestions.getScore())){
                ErrorNotebooksQuestions errorNotebooksQuestions = new ErrorNotebooksQuestions();
                errorNotebooksQuestions.setStatus(0);
                errorNotebooksQuestions.setStudentId(String.valueOf(examGrades.getStudentId()));
                errorNotebooksQuestions.setErrorSource(1);
                errorNotebooksQuestions.setErrorQuestion(examQuestions.getQuestionTitle());
                errorNotebooksQuestions.setQuestionType(String.valueOf(3));
                errorNotebooksQuestions.setStudentAnswer(examGrades.getStudentAnswer());
                fErrorNotebooksQuestionsService.save(errorNotebooksQuestions);
            }
            examGradesMapper.updateById(examGrades);
            ExamStudentRecords one = getOtherScore(examGrades.getExamRecordId(), examGrades.getStudentId());
            score += examGrades.getScore();
            BigDecimal oldScore = one.getScore();
            oldScore = oldScore.add(new BigDecimal(score));
            one.setScore(oldScore);
            one.setExamStatus(3);
            score=0.0;
            eStudentRecordsService.updateById(one);
        }
    }

    //计算学生主观题以外的分数
    public ExamStudentRecords getOtherScore(Integer examRecordId, Integer studentId) {
        //获取考试记录
        ExamStudentRecords one = eStudentRecordsService.getOne(new LambdaQueryWrapper<ExamStudentRecords>().eq(ExamStudentRecords::getStudentId, studentId).eq(ExamStudentRecords::getExamRecordId, examRecordId));
        //获取考试题目
        List<ExamQuestions> list = examQuestionsService.list(new LambdaQueryWrapper<ExamQuestions>().eq(ExamQuestions::getExamRecordId, examRecordId)).stream().filter(item -> !item.getQuestionType().equals("3")).toList();
        //创建存储题目答案和分数的集合
        HashMap<Integer, String> optionAnswer = new HashMap<>();
        HashMap<Integer,Integer> optionScore=new HashMap<>();
        //将题目的答案和分数存放到集合中
        for (ExamQuestions examQuestions : list) {
            List<Integer> anwerList = examOptionAnswerMapper.selectList(new LambdaQueryWrapper<ExamOptionAnswer>().eq(ExamOptionAnswer::getQuestionId, examQuestions.getId()))
                    .stream().filter(item -> item.getIsCorrect() == 1).map(ExamOptionAnswer::getId).toList();
            String string = anwerList.toString();
            optionAnswer.put(examQuestions.getId(),string.substring(1,string.length() - 1));
            optionScore.put(examQuestions.getId(),examQuestions.getScore());
        }
        //错误题目集合
        List<ExamQuestions> errorQuestions = new ArrayList<>();
        //查询学生考试记录
        List<ExamGrades> grades = examGradesMapper.selectList(new LambdaQueryWrapper<ExamGrades>().eq(ExamGrades::getStudentId, studentId).eq(ExamGrades::getExamRecordId, examRecordId));
        //计算学生分数
        double sorce=0.0;
        for (ExamGrades examGrades : grades) {
            String answer = optionAnswer.get(examGrades.getQuestionId());
            if(answer!=null){
                answer = answer.replace(" ", "");
                if (answer.equals(examGrades.getStudentAnswer())) {
                    sorce += (double) optionScore.get(examGrades.getQuestionId());
                }
            }
        }
        BigDecimal odlScore =one.getScore();
        BigDecimal score = odlScore.add(BigDecimal.valueOf(sorce));
        one.setScore(score);
        return one;
    }
}





